import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from '@/views/LoginView.vue'
import IndexView from '@/views/IndexView.vue'
import store from '@/store/index.js'
import { getToken } from '@/util/storage.js'

/*点击2次同一个路由，报错显示路由重复问题*/
//备份原型对象已有的push|replace方法
let push = VueRouter.prototype.push;
let replace = VueRouter.prototype.replace;
//重写VueRouter.prototype原型对象的push|replace方法
VueRouter.prototype.push = function (location) {
    //调用push方法且篡改push方法内部this指向->vueRouter类的实例
    push.call(this, location, () => { }, () => { });
}
VueRouter.prototype.replace = function (location) {
    //调用push方法且篡改push方法内部this指向->vueRouter类的实例
    replace.apply(this, [location, () => { }, () => { }]);
}

Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/login'
},
{
  name: 'login',
  path: '/login',
  component: LoginView
},
{
  name: '/index',
  path: '/index',
  component: IndexView,
  children: [
    {
      path: '/index',
      name: '/index',
      components: {menuUrl:() => import('@/views/modules/YmMain.vue')}
    },
    {
      path: '/user',
      name: '/user',
      components: {menuUrl:() => import('@/views/modules/YmUser.vue')}
    },
    {
      path: '/dept',
      name: '/dept',
      components: {menuUrl:() => import('@/views/modules/YmDept.vue')}
    },
    {
      path: '/logs',
      name: '/logs',
      components: {menuUrl:() => import('@/views/modules/YmLogs.vue')}
    }
  ]
}]

const router = new VueRouter({
  routes
})

// 不需要登录就能访问的路径
const anonUrls = ['/', '/login']
//全局前置守卫，判断是否有token，如果没有token跳转到登录页面
router.beforeEach((to,from,next) => {
  if(anonUrls.includes(to.path)){
    next()
  }else{
    const token = getToken();
    if(token === null || token === ''){
      next('/login')
    }else{
      next()
    }
  }
})

export default router
